// websocketPlugin.js
import WebSocketService from "./Websocket.js";

const socketInstance = new WebSocketService();
const messageHandlers = new Set();

const websocketPlugin = {
    install(Vue) {
        Vue.prototype.$websocket = socketInstance;

        // 提供显式初始化连接的方法，避免自动连接导致挂载失败
        Vue.prototype.$initWebSocket = function () {
            socketInstance.connect((data) => {
                messageHandlers.forEach(fn => fn(data));
            });
        };
        
        Vue.prototype.$registerWebSocketHandler = function (fn) {
            if (typeof fn === 'function') {
                messageHandlers.add(fn);
            }
        };

        Vue.prototype.$unregisterWebSocketHandler = function (fn) {
            messageHandlers.delete(fn);
        };
    }
};

export default websocketPlugin;
